import json
import pandas
import requests
from websockets.sync.client import connect


class TqsdkDatafeed(object):
    tqSec = 1000000000
    intervalMap = {
        '1min': 1, '5min': 5, '15min': 15, '30min': 30, 'H': 60,
        'D': 1440, 'W': 1440, 'M': 1440
    }

    @staticmethod
    def get_tags(data):
        tags = data["py"].replace("zhishu", "").replace("zs", "").replace("，", ",")
        tags = set(tags.split(","))
        tags.add(data["ins_name"])
        return ",".join(tags)

    def get_detail(self):
        results = list()
        respond = requests.get('https://openmd.shinnytech.com/t/md/symbols/latest.json').json()
        for item in respond.values():
            if not item["expired"] and item['class'] == 'FUTURE':
                results.append({
                    "title": item["ins_name"], "symbol": item["ins_id"], "product": item["product_id"],
                    "exchange": item["exchange_id"], "market": "china_future",
                    "kq_instrument_id": item["instrument_id"],
                    "pre_volume": item["pre_volume"],
                    "volume_multiple": item["volume_multiple"],
                    "expire_datetime": pandas.to_datetime(item["expire_datetime"], origin='1970-01-01 08:00:00', unit="s"),
                    "price_tick": item["price_tick"],
                    "price_decs": item["price_decs"],
                    "trading_time": item["trading_time"],
                    "commission": round(item["commission"], 3),
                    "margin": round(item["margin"], 3),
                    "tags": self.get_tags(item)
                })
        return pandas.DataFrame(results).fillna(0)

    def get_history(self, symbol, interval):
        second = self.intervalMap[interval] * 60 * self.tqSec
        with connect('wss://openmd.shinnytech.com/t/md/front/mobile') as ws:
            ws.recv()
            ws.send('{"aid":"peek_message"}')
            ws.recv()
            ws.send('{"aid":"peek_message"}')
            ws.send('{"aid":"set_chart","chart_id":"PC_kline_chart","ins_list":"%s","duration":"%d","view_width":2000}' % (symbol, second))
            ws.recv()
            ws.send('{"aid":"peek_message"}')
            respond = ws.recv()
            respond = json.loads(respond)
            respond = respond['data'][0]['klines'][symbol][str(second)]['data']
            respond = pandas.DataFrame(respond.values())
            respond = respond[['datetime', 'open', 'high', 'low', 'close', 'volume']]
            respond['datetime'] = pandas.to_datetime(respond['datetime'] / self.tqSec, origin='1970-01-01 08:00:00', unit='s')
            return respond


__all__ = [TqsdkDatafeed]
